package com.zhang.topic.list;

/**
 * @title: 环形链表
 * @author: zhang
 * @date: 2022/4/7 08:10
 * 给你一个链表的头节点 head ，判断链表中是否有环。
 * 如果链表中有某个节点，可以通过连续跟踪 next 指针再次到达，则链表中存在环。
 */
public class LeetCode141_142 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**判断链表是否有环*/
    public static boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode slowPtr = head, fastPtr = head;
        while (fastPtr.next != null && fastPtr.next.next != null) {
            slowPtr = slowPtr.next;
            fastPtr = fastPtr.next.next;
            if (slowPtr == fastPtr) {
                return true;
            }
        }
        return false;
    }

    /**判断链表是否有环，如果有环找到环入口*/
    public static ListNode hasCycle1(ListNode head) {
        if (head == null) return null;
        ListNode slowPtr = head, fastPtr = head;
        while (fastPtr.next != null && fastPtr.next.next != null) {
            slowPtr = slowPtr.next;
            fastPtr = fastPtr.next.next;
            if (slowPtr == fastPtr) {
                slowPtr = head;
                while (slowPtr != fastPtr){
                    fastPtr = fastPtr.next;
                    slowPtr = slowPtr.next;
                }
                return slowPtr;
            }
        }
        return null;
    }
}
